<?php
/**
 * 材料供应商
 * (model)
 */
namespace App\Models\Basics;

use App\Models\Product\ProductMaterial;
use App\Models\Product\ProductSupplierM;
use Illuminate\Database\Eloquent\Model;
class SupplierM extends Model
{
    protected $table = 'b_supplier';

    public $timestamps = false;

    protected $guarded = [];

    public static $_shipFeeType = [
        1 => '含运费',
        2 => '不含运费',
    ];

    //审核状态
    const AUDIT_NO = 0; //未审核
    const AUDIT_SUCCESS = 1; //已审核
    public static $_auditStatus = [
        self::AUDIT_NO => '未审核',
        self::AUDIT_SUCCESS => '已审核'
    ];

    //供应商状态
    const STATUS_YES = 1; //启用
    const STATUS_NO  = 2; //停用
    public static $_status = [
        self::STATUS_YES => '启用',
        self::STATUS_NO => '停用'
    ];

    //供应商类型
    const TYPE_SKU = 1; //成品
    const TYPE_MATERIAL = 2; //材料
    public static $_type = [
        self::TYPE_SKU => '成品',
        self::TYPE_MATERIAL => '材料'
    ];

    public function supplier_contacts(){
        return $this->hasMany(SupplierContact::class,'supplier_id');
    }

    public function supplier_account(){
        return $this->hasOne(SupplierAccount::class,'supplier_id');
    }

    public function supplier_file(){
        return $this->hasOne(SupplierFile::class,'supplier_id');
    }

    public function settlement_method(){
        return $this->belongsTo(SettlementMethod::class,'settlement_method_id');
    }

    //第三个参数是定义此关联的模型(SupplierM)在连接表(product_supplier_m)里的外键名，第四个参数是另一个模型(ProductSku)在连接表里的外键名
    public function material(){
        return $this->belongsToMany(ProductMaterial::class,'product_supplier_m','supplier_id','material_id')
            ->using(ProductSupplierM::class)
            ->withPivot('supplier_material_no', 'quote_price', 'quote_currency', 'audit_status', 'audit_time');
    }

    public static function options($flag = true){
        $query = self::query()->where('type',2);
        if(!$flag){
            $query = $query->where('audit_status',1)->where('status',1);
        }
        $res = $query->get()->map(function ($model){
            return collect(['name' => $model->short_name.'-'.$model->name,
                'id' => $model->id]);
        });
        return $res->pluck('name','id');
    }

    public static function getNameById($id,$flag = true)
    {
        $query = self::query()->where('type',2);
        if(!$flag){
            $query = $query->where('audit_status',1)->where('status',1);
        }
        return $query->where('id',$id)->value('name');
    }

    public static function getIdByCode($code,$flag = true)
    {
        $query = self::query()->where('type',2);
        if(!$flag){
            $query = $query->where('audit_status',1)->where('status',1);
        }
        return $query->where('code',$code)->value('id');
    }
}
